package logic

import (
	"api/internal/svc"
	"api/internal/types"
	"api/model/mysql"
	"context"
	"github.com/google/uuid"
	"mooc_srv/moocclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderAddLogic) OrderAdd(req *types.OrderAddRequest) (resp *types.Response, err error) {

	gs := mysql.Goods{}
	err = gs.WhereGoods(req.GoodsId)
	if err != nil {
		return &types.Response{
			Msg:  "商品信息获取失败",
			Code: 500,
			Data: nil,
		}, err
	}
	if gs.ID == 0 {
		return &types.Response{
			Msg:  "商品不存在",
			Code: 500,
			Data: nil,
		}, err
	}
	if gs.GoodsSum < int(req.OrderSum) {
		return &types.Response{
			Msg:  "库存不足",
			Code: 500,
			Data: nil,
		}, err
	}
	OrderSn := uuid.NewString()
	Amount := gs.GoodsPrice * float64(req.OrderSum)
	add, err := l.svcCtx.Mooc.OrderAdd(l.ctx, &moocclient.OrderAddRequest{
		Userid:      req.Userid,
		GoodsId:     req.GoodsId,
		OrderSum:    req.OrderSum,
		OrderPay:    req.OrderPay,
		OrderSn:     OrderSn,
		OrderAmount: float32(Amount),
	})
	if err != nil {
		return &types.Response{
			Msg:  "下单失败",
			Code: 500,
			Data: nil,
		}, err
	}
	return &types.Response{
		Msg:  "下单成功",
		Code: 200,
		Data: map[string]interface{}{
			"orderId": add.OrderId,
			"url":     add.Url,
		},
	}, nil
}
